package com.green.web.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.green.common.util.TokenUtil;
import com.green.dao.cache.XMemcachedCache;
import com.green.service.common.SpringUtil;


/**
 * 会话辅助类
 * 
 * @author fengwenjin
 * 
 */
public class SessionHelper {

	private static final String SID = "sid";
	private static final String ATTRIBUTE = "attribute";
	private static final XMemcachedCache memcachedClient = SpringUtil.getBean("xMemcachedCache");
	
	/**
	 * 获取会话ID
	 * 
	 * @return String
	 */
	public static String getId() {
		HttpServletRequest request = WebContext.getRequest();
		String sid = (String) request.getAttribute(SID);
		if(sid == null){
			if(request.getQueryString() != null && request.getQueryString().startsWith(SID)){
				sid = request.getParameter(SID);
			}
		}
		if(sid == null){
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals(SID)) {
						sid = cookie.getValue();
						break;
					}
				}
			}
		}
		return sid;
	}
	
	public static void create(String uid) {
		String sid = TokenUtil.encode(uid);
		Cookie cookie = new Cookie(SID, sid);
		cookie.setPath("/");
		WebContext.getResponse().addCookie(cookie);
		WebContext.getRequest().setAttribute(SID, sid);
	}

	/**
	 * 会话失效
	 */
	public static void destroy() {
		String key = getId();
		if(key != null){
			String uid = TokenUtil.decode(key);
			if(uid != null){
				memcachedClient.delete(uid);
				PermissionHelper.inValidate();	
			}
		}
	}

	/**
	 * 获取会话属性
	 * 
	 * @param name
	 * @return Object
	 */
	@SuppressWarnings("unchecked")
	public static Object getAttribute(String name) {
		Object value = null;
		HttpServletRequest request = WebContext.getRequest();
		Map<String, Object> map = (Map<String, Object>) request.getAttribute(ATTRIBUTE);
		if(map == null){
			String key = getId();
			if(key != null){
				String uid = TokenUtil.decode(key);
				if(uid != null){
					map = (Map<String, Object>) memcachedClient.get(uid);
				}
			}
		}
		if(map != null){
			value = map.get(name);
		}
		request.setAttribute(ATTRIBUTE, map);
		return value;
	}

	/**
	 * 设置会话属性
	 * 
	 * @param name
	 * @param value
	 */
	@SuppressWarnings("unchecked")
	public static void setAttribute(String name, Object value) {
		String key = getId();
		if(key != null){
			String uid = TokenUtil.decode(key);
			if(uid != null){
				Map<String, Object> map = (Map<String, Object>) memcachedClient.get(uid);
				if(map == null){
					map = new HashMap<String, Object>();
				}
				map.put(name, value);
				memcachedClient.set(uid, 1800, map);
			}
		}
	}
	
	/**
	 * 删除会话属性
	 * 
	 * @param name
	 */
	public static void removeAttribute(String name) {
		setAttribute(name, null);
	}

}
